package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @author zhangxiaofanfan
 * @date 2024-05-29 08:42:27
 */
public class HotCode035 {
    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(2);
        lruCache.put(1, 1);
        lruCache.put(2, 2);
        System.out.println(lruCache.get(1));
        lruCache.put(3, 3);
        System.out.println(lruCache.get(2));
        lruCache.put(4, 4);
        System.out.println(lruCache.get(1));
        System.out.println(lruCache.get(3));
        System.out.println(lruCache.get(4));
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
class LRUCache {
    private final Node header;
    private final Node tail;
    private final Map<Integer, Node> map;
    private final Integer capacity;

    public LRUCache(int capacity) {
        this.map = new HashMap<>();
        header = new Node();
        tail = new Node();
        header.next = tail;
        tail.pre = header;
        this.capacity = capacity;
    }

    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        Node node = map.get(key);
        remove2End(node);
        return node.value;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            Node node = map.get(key);
            node.value = value;
            remove2End(node);
        }
        if (map.size() >= capacity) {
            Node first = header.next;
            map.remove(first.value);
            header.next = first.next;
        }
        Node newNode = new Node();
        newNode.value = value;
        map.put(key, newNode);
        toEnd(newNode);
    }

    public void remove2End(Node node) {
        remove(node);
        toEnd(node);
    }

    public void remove(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    public void toEnd(Node node) {
        tail.pre.next = node;
        node.next = tail;
        node.pre = tail.pre;
        tail.pre = node;
    }

    static class Node {
        Node pre;
        Node next;
        int value;
    }
}
